import logging

from pylons import request, response, session, tmpl_context as c
from pylons.controllers.util import abort, redirect_to

from datetime import date, datetime

from horseanalysis.lib.base import render
from horseanalysis.controllers.application import ApplicationController
from horseanalysis.model.race import Race
from horseanalysis.model.win_place import WinPlace
from horseanalysis.model.quinella import Quinella
from horseanalysis.model.quinella_place import QuinellaPlace
from horseanalysis.model.race_batch import RaceBatch
from horseanalysis.model.betting_scheme import BettingScheme
from horseanalysis.model.probability_sets.quinella_probability_result import QuinellaProbabilityResult
from horseanalysis.model.probability_sets.quinella_place_probability_result import QuinellaPlaceProbabilityResult
from horseanalysis.model.probability_sets.place_probability_result import PlaceProbabilityResult

log = logging.getLogger(__name__)

FROM_EXPECTED_RETURN = 0.9

class RacesController(ApplicationController):
  def index(self):
    c.races = Race.get_races()
    return render('/races/index.html')
  
  def show(self, id, batch = None):
    c.race = Race.get_race(id)
    if c.race:
      c.race_batches = RaceBatch.get_race_batches(c.race)
      if batch:
        c.race_batch = RaceBatch.get_batch(batch)
      else:
        c.race_batch = RaceBatch.get_latest_batch(c.race)
      c.win_place = WinPlace.get_odds(c.race_batch)
      c.quinella = Quinella.get_odds(c.race_batch)
      c.quinella_place = QuinellaPlace.get_odds(c.race_batch)
      
      # For betting suggestion
      c.schemes = BettingScheme.get_all_schemes()
      c.place_prob_sets = {}
      c.quinella_prob_sets = {}
      c.qplace_prob_sets = {}

      for scheme in c.schemes:
        c.place_prob_sets[scheme.name]=PlaceProbabilityResult.get_by_expected_return(c.race_batch, FROM_EXPECTED_RETURN)
        c.quinella_prob_sets[scheme.name]=QuinellaProbabilityResult.get_by_expected_return(c.race_batch, FROM_EXPECTED_RETURN)
        c.qplace_prob_sets[scheme.name]=QuinellaPlaceProbabilityResult.get_by_expected_return(c.race_batch, FROM_EXPECTED_RETURN)
    
    return render('/races/show.html')